package com.youbug.system.config.coverter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.youbug.system.config.annotation.UseDicTrans;
import com.youbug.system.entity.Dictionary;
import com.youbug.system.service.IDictionaryService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
@Component
public class DicCoverter implements Converter<String>, ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @Override
    public String convertToJavaData(ReadCellData<?> cellData,
                                    ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) throws Exception {
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value,
                                               ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) throws Exception {
        Field field = contentProperty.getField();

        UseDicTrans dicTrans = field.getAnnotation(UseDicTrans.class);
        if(dicTrans != null){
            String dicTypeCode = dicTrans.dicTypeCode();

            IDictionaryService dictionaryService = context.getBean(IDictionaryService.class);
            Dictionary dictionary = dictionaryService.getOneByTypeAndCode(dicTypeCode, value);

            return new WriteCellData<>(dictionary.getValue());
        }
        return new WriteCellData<>(value);
    }
}
